package org.example.config;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.impl.config.BaseCacheConfiguration;
import org.ehcache.jsr107.EhcacheCachingProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.net.URI;

@Configuration
//@EnableCaching
public class MyCacheConfiguration {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    private Resource getResource(String locationPattern){
        Resource[] resources = null;
        try {
            resources = resourcePatternResolver.getResources(locationPattern);
        } catch (IOException e) {
            //throw new RuntimeException(e);
        }
        if(ObjectUtils.isEmpty(resources)) return null;
        return resources[0];
    }

    @Bean
    public CacheManager ehcacheManager() {
        Resource resource = getResource(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "ehcache3.xml");
        URI uri = null;
        try {
            uri = resource.getURI();
            logger.info("load ehcache config--> {}", uri);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        EhcacheCachingProvider ehcacheCachingProvider = new EhcacheCachingProvider();
        javax.cache.CacheManager jcacheManager = ehcacheCachingProvider.getCacheManager(uri, getClass().getClassLoader());
        JCacheCacheManager jCacheCacheManager = new JCacheCacheManager(jcacheManager);
        return jCacheCacheManager;
    }

}
